package com.cjst.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import sun.misc.BASE64Encoder;


import freemarker.template.Template;

@Component
public class DocUtil {
    //	 @Value("${tp.img}")
//	 private String tpImg;
    private FreeMarkerConfigurer freeMarkerConfigurer;
    private static ApplicationContext applicationContext;
    public static void setApplicationContext(ConfigurableApplicationContext context) {
        DocUtil.applicationContext = context;
    }
    public void wordDown(HttpServletResponse response,HttpServletRequest request, Map<String, Object> root,String fileName) throws Exception{
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/msword");
        fileName = new String(fileName.getBytes(),"ISO-8859-1");//设置编码，文件名才能使用中文
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename="+fileName);
        freeMarkerConfigurer=(FreeMarkerConfigurer) applicationContext.getBean(FreeMarkerConfigurer.class);
        freeMarkerConfigurer.getConfiguration().setClassForTemplateLoading(getClass(), "/");
        Template template = freeMarkerConfigurer.getConfiguration().getTemplate("/dy/dy.ftl");
        String webapp = request.getServletContext().getRealPath("/");
        template.process(root, new OutputStreamWriter(response.getOutputStream()));
    }
    //获得图片的base64码
    public static String getImageBase(String src) throws Exception {
        if (src == null || src == "") {
            return "";
        }
        File file = new File(src);
        if (!file.exists()) {
            return "";
        }
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }
}
